import { CloseCircleOutlined } from '@ant-design/icons';
import { Button, Card, Col, Form, Input, InputNumber,Popover, Row, Select } from 'antd';
import React, { FC, useState, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { connect, Dispatch } from 'umi';
import { getPageQuery, isEmpty } from '@/utils/utils';
import styles from './style.less';


import { getDict } from '@/services/dict'
import { history } from 'umi';


type InternalNamePath = (string | number)[];

const { Option } = Select;

const fieldLabels = {
    type: '类型',
    desc: '描述',
    label: '标签',
    value: '键值',
    sort: '排序'
};


interface DictFormProps {
    dispatch: Dispatch<any>;
    submitting: boolean;
}

interface ErrorField {
    name: InternalNamePath;
    errors: string[];
}

const DictForm: FC<DictFormProps> = ({ submitting, dispatch }) => {
    const [form] = Form.useForm();
    const [error, setError] = useState<ErrorField[]>([]);

    useEffect(() => {
        const query:any = getPageQuery()
        form.setFieldsValue(query)
        // debugger
        const ID:number = parseInt(query.ID) ||0
        form.setFieldsValue({...query,...{ID:ID}})
        if(ID>0){
            getDict({id:ID}).then(res=>{
                const rlt = res.results[0]
                form.setFieldsValue({...query,...rlt});
            })
        }
    }, [])
    const getErrorInfo = (errors: ErrorField[]) => {
        const errorCount = errors.filter((item) => item.errors.length > 0).length;
        if (!errors || errorCount === 0) {
            return null;
        }
        const scrollToField = (fieldKey: string) => {
            const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
            if (labelNode) {
                labelNode.scrollIntoView(true);
            }
        };
        const errorList = errors.map((err) => {
            if (!err || err.errors.length === 0) {
                return null;
            }
            const key = err.name[0] as string;
            return (
                <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
                    <CloseCircleOutlined className={styles.errorIcon} />
                    <div className={styles.errorMessage}>{err.errors[0]}</div>
                    <div className={styles.errorField}>{fieldLabels[key]}</div>
                </li>
            );
        });
        return (
            <span className={styles.errorIcon}>
                <Popover
                    title="表单校验信息"
                    content={errorList}
                    overlayClassName={styles.errorPopover}
                    trigger="click"
                    getPopupContainer={(trigger: HTMLElement) => {
                        if (trigger && trigger.parentNode) {
                            return trigger.parentNode as HTMLElement;
                        }
                        return trigger;
                    }}
                >
                    <CloseCircleOutlined />
                </Popover>
                {errorCount}
            </span>
        );
    };

    const onFinish = (values: { [key: string]: any }) => {
        setError([]);
        const query = getPageQuery()
        const ID: any = query.ID || undefined
        dispatch({
            type: 'dict/saveDict',
            payload: { ...values, ...{ id: ID } },
        });
        history.replace({
            pathname: '/setting/dict/list'
        });
    };

    const onFinishFailed = (errorInfo: any) => {
        setError(errorInfo.errorFields);
    };
    return (
        <Form
            form={form}
            layout="vertical"
            hideRequiredMark
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
        >
            <PageContainer >
                <Card title="" className={styles.card} bordered={false}>
                    <Row gutter={16}>
                        <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                            <Form.Item
                                label={fieldLabels.type}
                                name="type"
                                rules={[{ required: true, message: '请输入类型' }]}
                            >
                                <Input
                                    style={{ width: '100%' }}
                                    placeholder="请输入类型"
                                />
                            </Form.Item>
                        </Col>
                        <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                            <Form.Item
                                label={fieldLabels.desc}
                                name="desc"
                                rules={[{ required: true, message: '请输入描述' }]}
                            >
                                <Input
                                    style={{ width: '100%' }}
                                    placeholder="请输入描述"
                                />
                            </Form.Item>
                        </Col>

                    </Row>
                    <Row gutter={16}>
                        <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                            <Form.Item
                                label={fieldLabels.label}
                                name="label"
                                rules={[{ required: true, message: '请输入标签' }]}
                            >
                                <Input
                                    style={{ width: '100%' }}
                                    placeholder="请输入标签"
                                />
                            </Form.Item>
                        </Col>
                        <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                            <Form.Item
                                label={fieldLabels.value}
                                name="value"
                                rules={[{ required: false, message: '请输入键值' }]}
                            >
                                <Input
                                    style={{ width: '100%' }}
                                    placeholder="请输入键值"
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
                            <Form.Item
                                label={fieldLabels.sort}
                                name="sort"
                                rules={[{ required: true, message: '请输入排序' }]}
                            >
                                <InputNumber 
                                    style={{ width: '100%' }}
                                    placeholder="请输入排序"
                                    min={0}
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                </Card>


            </PageContainer>
            <FooterToolbar>
                {getErrorInfo(error)}
                <Button type="primary" onClick={() => form?.submit()} loading={submitting}>
                    提交
        </Button>
            </FooterToolbar>
        </Form>
    );
};

export default connect(({ loading }: { loading: { effects: { [key: string]: boolean } } }) => ({
    submitting: loading.effects['dict/saveDict'],
}))(DictForm);
